/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState } from 'react';
import { Button, Tree, Card, Space, Layout, message, Modal, Checkbox, Divider } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useLocation, connect } from 'umi';
import styles from './index.less';
import { updateUserAuthorize, authorize, getUserInfo } from '@/services/admin/editMenu';
import isArray from 'lodash/isArray';
import {
  userAuthorityRoutes,
  expandRoutes,
  getAuthKey,
  getAuthDetailList,
  getAuthRoute,
} from '@/utils/admin/menu';
import AuthSelect from '@/components/_page/admin/editMenu/authSelect';
import type { ConnectState } from '@/models/connect';
import type { BasicLayoutProps as ProLayoutProps } from '@ant-design/pro-layout';
import {
  filterPermissionsCheckKeys,
  filterPermissionsCheckKeysByParent,
  patchCheckKeysByPermissions,
  useTitleRender,
} from '@/components/_page/admin/editMenu/authority-extend';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';

interface AdminMenuEditProps extends ProLayoutProps {
  routes: any[];
  currentUser: any;
}

const { Footer, Content } = Layout;
const EditMenu: React.FC<AdminMenuEditProps> = (props) => {
  const location = useLocation();
  const { routes, history, currentUser } = props;
  const authorityRoutes = userAuthorityRoutes(routes[1]?.routes[0]?.routes);
  const authorityTreeData = authorityRoutes
    .map((item: any) => ({ ...item, key: '' }))
    .map((item1: any) => [item1]);
  const authDetailList = expandRoutes(routes[1]?.routes[0]?.routes);
  const allCheckedKeys = authDetailList.map((item: any) => item.key);
  const [permissionsCheckKeys, setPermissionsCheckKeys] = useState<CheckboxValueType[]>([]);
  const [checkKeys, setCheckKeys] = useState<any[]>([]);
  const [checkUserData, setCheckUserData] = useState<any[]>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [authDetails, setAuthDetails] = useState<string[]>([]);
  const [userData, setUserData] = useState<any>();

  const onCheck = (data: any, checkData: any) => {
    data = data.filter((item: any) => !checkKeys.includes(item));
    let checkKey: any[] = [];
    if (data.length) {
      checkKey = [...checkKeys, ...data].filter((item: any) => item);
    } else {
      if (checkData.node && checkData.node.children && checkData.node.children.length) {
        const deleteKeys = checkData.node.children.map((item: any) => item.key);
        checkKey = checkKeys.filter((item: any) => !deleteKeys.includes(item));
      } else {
        checkKey = checkKeys.filter((item: any) => item !== checkData.node.key);
      }
    }
    setCheckKeys(checkKey);
  };

  const onSubmit = () => {
    const { managerInfo, isManager } = currentUser;
    if (!isManager) {
      message.error(`请联系管理员${managerInfo.name}添加权限`);
      return;
    }
    const menu_ids = getAuthKey(authDetailList, checkKeys).concat(permissionsCheckKeys as number[]);
    const authArr = isArray(menu_ids) ? menu_ids : [menu_ids];
    setAuthDetails(getAuthDetailList(authDetailList, authArr));
    if (isArray(checkUserData)) {
      if (!checkUserData.length) {
        message.error('请最少选择一人授权');
        return;
      }
      if (!menu_ids.length) {
        message.error('请最少选择一项权限');
        return;
      }

      authorize({
        user_ids: checkUserData,
        menu_ids,
      }).then((res: any) => {
        if (res.code == 0) {
          setVisible(true);
          message.success('授权成功');
        } else {
          message.error(res.msg);
        }
      });
    } else {
      updateUserAuthorize({ user_id: checkUserData, menu_ids }).then((res: any) => {
        if (res.code == 0) {
          setVisible(true);
          message.success('授权成功');
        } else {
          message.error(res.msg);
        }
      });
    }
  };

  const handleOk = () => {
    setVisible(false);
    history?.push('/f/admin/menu');
  };

  const handleSelect = (data: any) => {
    setCheckUserData(data);
  };

  const onChancel = () => {
    history?.push('/f/admin/menu');
  };

  // 补充渲染功能组件权限
  const titleRender = useTitleRender();

  // 功能组件权限选择
  const handleCheckboxChange = (values: CheckboxValueType[]) => {
    setPermissionsCheckKeys(values);
    setCheckKeys(patchCheckKeysByPermissions(values, checkKeys));
  };

  useEffect(() => {
    const { query }: any = location;
    if (query.userid) {
      getUserInfo({ user_id: query.userid }).then(({ code, data, msg }) => {
        if (code == 0) {
          setUserData(data);
          setCheckKeys(getAuthRoute(data.menu_list));
          setPermissionsCheckKeys(filterPermissionsCheckKeys(data.menu_list));
        } else {
          message.error(msg);
        }
      });
    }
  }, [location.search]);

  useEffect(() => {
    // 父级权限变更，动态变更组件权限
    if (permissionsCheckKeys.length === 0) return;
    setPermissionsCheckKeys(filterPermissionsCheckKeysByParent(permissionsCheckKeys, checkKeys));
  }, [checkKeys]);

  return (
    <PageContainer title={false} className={styles.edit}>
      <Layout>
        <Content>
          <Card className={styles.edit_card}>
            <AuthSelect handleSelect={handleSelect} userData={userData}></AuthSelect>
            <Divider />
            <Checkbox.Group
              onChange={handleCheckboxChange}
              value={permissionsCheckKeys}
              className={styles.edit_checkbox}
            >
              {authorityTreeData.map((item: any, index: number) => (
                <Tree
                  key={index}
                  checkedKeys={checkKeys}
                  checkable
                  treeData={item}
                  defaultExpandAll
                  onCheck={onCheck}
                  titleRender={titleRender}
                />
              ))}
            </Checkbox.Group>
          </Card>
        </Content>
        <Footer>
          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Space>
              <Checkbox
                onChange={(e: any) => {
                  if (e.target.checked) {
                    setCheckKeys(allCheckedKeys);
                  } else {
                    setCheckKeys([]);
                  }
                }}
              >
                全选
              </Checkbox>
              <Button type='primary' onClick={onSubmit}>
                确定
              </Button>
              <Button onClick={onChancel}>取消授权</Button>
            </Space>
          </div>
        </Footer>
      </Layout>
      <Modal
        title='授权详情'
        visible={visible}
        keyboard={false}
        maskClosable={false}
        closable={false}
        footer={[
          <Button type='primary' key='goBack' size='middle' onClick={handleOk}>
            返回上一页
          </Button>,
        ]}
      >
        {authDetails.length ? authDetails : <div style={{ color: 'red' }}>暂无授权信息</div>}
      </Modal>
    </PageContainer>
  );
};

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(React.memo(EditMenu));
